'use strict'

import { app, protocol, BrowserWindow, Menu, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
// import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
// import {Menu} from "element-ui";
const isDevelopment = process.env.NODE_ENV !== 'production'

// Socket

// WebSocket Config
const ws = require('nodejs-websocket')
const PORT = 12300
// eslint-disable-next-line no-unused-vars
let serverConnection = null
let clientConnection = null

const server = ws.createServer(connect => {
  console.log("New Connection")
  connect.on('text', data => {
    console.log("Received Data: " + data)
    let dataJson = JSON.parse(data)
    switch (dataJson.type) {
      case 'handshake':
        // 握手
          if (dataJson.data.model === 'server') {
            serverConnection = connect
          } else {
            clientConnection = connect
          }
        break
      case 'responseSize':
          if(serverConnection != null) {
            serverConnection.sendText(data)
          }
        // eslint-disable-next-line no-fallthrough
      default:
        if(clientConnection != null) {
          clientConnection.sendText(data)
        }
        // 配置更新
        break
    }


    // 连接断开 触发close事件
    connect.on("close", (code, reason) => {
      console.log("connection closed")
      code && console.log(code)
      reason && console.log(reason)
    })

    // error：监听服务异常事件，放置因报错而断掉整个服务。
    connect.on('error', ()=>{
      // 如果触发了close事件，就会走error异常事件(刷新也会)，所以必须加error
      console.log('连接出现异常')
    })

  })
})

server.listen(PORT, () => {
  console.log('WebSocket服务端启动成功')
})
// Socket End

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

// Create the browser window.
const win = null

function createWindows() {

  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html#/')
  }
  return win
}

export function createMinWindow () {
  Menu.setApplicationMenu(null) // 关闭子窗口菜单栏
  const modalPath = process.env.NODE_ENV === 'development'
      ? 'http://localhost:9080/#/client'
      : `file://${__dirname}/index.html#/client`
// 使用hash对子页面跳转，这是vue的路由思想
  let miniWindow = new BrowserWindow({
    width: 600,
    height: 400,
    webPreferences: {
      webSecurity: false,
      nodeIntegration: true
    },
    parent: win // mainWindow是主窗口
  })

  miniWindow.loadURL(modalPath)

  miniWindow.on('closed', () => {
    miniWindow = null
  })
}


// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindows()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    // try {
    //   await installExtension(VUEJS_DEVTOOLS)
    // } catch (e) {
    //   console.error('Vue Devtools failed to install:', e.toString())
    // }
  }
  this.win = createWindows()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}


ipcMain.on("openTele", (event, arg) => {
  console.log(arg);
  event.sender.send("reply", "ipcMain--->ipcRenderer");
  let newWindow;
  newWindow = new BrowserWindow({
    height: 563,
    useContentSize: true,
    width: 1000,
    parent: win
  });

  newWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL + "#/client");
  newWindow.on("closed", () => {
    newWindow = null;
  });
});